package top.zhangjianyong.entity;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ： zhangjianyong
 * @date ： 2022/8/19 9:49 PM
 */
@Data
public class Word {


    private String value;//词
    private Integer count;//出现次数
    private Integer totalLength;//
    private Double frequency;//频率
    private Double stone;//凝固程度
    private Double free;//自由程度

    private Map<String, Integer> left;
    private Integer leftTotal;
    private Map<String, Integer> right;
    private Integer rightTotal;

    public Word(String value, Integer totalLength) {
        this.value = value;
        this.totalLength = totalLength;
        this.count = 0;
        this.frequency = 0D;
        this.stone = 1D;
        this.free = 1D;
        this.left = new HashMap<>();
        this.right = new HashMap<>();
        this.leftTotal = 0;
        this.rightTotal = 0;
    }

    public void add() {
        this.count++;
        this.frequency = (double) this.count / this.totalLength;
    }

    public void left(String word) {
        this.leftTotal++;
        Integer count = this.left.getOrDefault(word, 0);
        count++;
        this.left.put(word, count);
    }

    public void right(String word) {
        this.rightTotal++;
        Integer count = this.right.getOrDefault(word, 0);
        count++;
        this.right.put(word, count);
    }

    public void stone(Double left, Double right) {
        if (left < right) {
            this.stone = left;
        } else {
            this.stone = right;
        }
    }

    public void free() {

        double leftFree = 0D;
        double rightFree = 0D;

        for (Map.Entry<String, Integer> entry : this.left.entrySet()) {
            double frequency = (double) entry.getValue() / leftTotal;
            leftFree -= Math.log(frequency) * frequency;
        }

        for (Map.Entry<String, Integer> entry : this.right.entrySet()) {
            double frequency = (double) entry.getValue() / rightTotal;
            rightFree -= Math.log(frequency) * frequency;
        }

        if (leftFree > rightFree) {
            this.free = leftFree;
        } else {
            this.free = rightFree;
        }
    }
}
